package com.example.voskdemo.service;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.vosk.Model;
import org.vosk.Recognizer;

import java.io.IOException;

@Service
public class VoskService {

    @Value("${vosk.sample-rate}")
    private int sampleRate;
    private final Model model;
    @Getter
    private Recognizer recognizer;

    public VoskService() throws IOException {
        String modelPath = "vosk-streaming-demo/models/vosk-model-small-cn-0.22";
        this.model = new Model(modelPath);
        this.recognizer = null;
    }

    public void startRecognition() throws IOException {
        if (recognizer == null) {
            recognizer = new Recognizer(model, sampleRate);
        }
    }

    public void stopRecognition() {
        if (recognizer != null) {
            recognizer.close();
            recognizer = null;
        }
    }

    public String recognizePartial(byte[] audioChunk) throws Exception {
        if (recognizer == null) {
            startRecognition();
        }

        if (recognizer.acceptWaveForm(audioChunk, audioChunk.length)) {
            return recognizer.getResult();
        } else {
            return "{\"partial\": \"" + recognizer.getPartialResult() + "\"}";
        }
    }

    public String getFinalResult() {
        if (recognizer != null) {
            return recognizer.getFinalResult();
        }
        return "{}";
    }
}